package com.its.us.mq.rocketmq;

import com.its.us.web.entity.sys.User;
import com.its.us.web.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

/**
 * @Author: master
 * @Date: 2020/11/30 14:47
 * @Version: 1.0
 */
@Slf4j
@Service
public class TestSendMsg {

    /*@Resource
    private MessageChannel output;

    @Async
    public void sendMsg(User user,String storeTag) {
        try {
            Map<String,Object> headers = new HashMap<>();
            headers.put(MessageConst.PROPERTY_TAGS,storeTag);
            MessageHeaders messageHeaders = new MessageHeaders(headers);
            Message<User> message = MessageBuilder.createMessage(user,messageHeaders);
            output.send(MessageBuilder.withPayload(JsonUtil.toJson(message)).build());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    @Autowired
    private DefaultMQProducer defaultMQProducer;

    @Async
    public void sendMsg(User user) {
        String msg = JsonUtil.toJson(user);
        Message sendMsg = new Message("store-topic", "tag-a", msg.getBytes());
        //默认3秒超时
        SendResult sendResult = null;
        try {
            sendResult = defaultMQProducer.send(sendMsg);
        } catch (MQClientException e) {
            e.printStackTrace();
        } catch (RemotingException e) {
            e.printStackTrace();
        } catch (MQBrokerException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        log.info("消息发送响应信息：" + sendResult.toString());
    }
}
